<template>
  <v-snackbar
    v-model="snackbar"
    multi-line
    :style="{ bottom: `90%` }"
    timeout="1000"
    @click="snackbar = false"
    :color="color"
  >
    <v-icon left>{{ text_ico }}</v-icon> {{ text }}
  </v-snackbar>
  <v-container class="container" fill-height>
    <v-row class="centered-row">
      <v-col cols="12" class="centered-col">
        <v-btn class="centered-btn" @click="openModal">创建任务</v-btn>
      </v-col>
      <v-col cols="12">
        <hr class="divider" />
        <v-text-field
          v-model="searchKeyword"
          label="搜索"
          @input="filterEntries"
        ></v-text-field>

        <!-- 删除按钮（居右对齐） -->
        <v-row class="justify-end mt-4">
          <v-btn v-if="selectedItems.length > 0" @click="deleteSelectedItems"
            >删除选中项</v-btn
          >
        </v-row>
        <v-table>
          <thead>
            <tr>
              <th class="text-left">
                <v-checkbox
                  v-model="selectAll"
                  @change="toggleAllSelection"
                ></v-checkbox>
              </th>
              <th class="text-left">标题</th>
              <th class="text-left">时间</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in filteredDesserts" :key="item.name">
              <td>
                <v-checkbox v-model="selectedItems" :value="item"></v-checkbox>
              </td>
              <td @click="navigateToItem(item.name)">{{ item.name }}</td>
              <td @click="navigateToItem(item.name)">{{ item.date }}</td>
              <td></td>
            </tr>
          </tbody>
        </v-table>
      </v-col>
    </v-row>
    <!-- 模态框 -->
    <v-dialog v-model="modalOpen" persistent max-width="50%">
      <v-card>
        <v-card-title>
          <span>任务标题</span>
        </v-card-title>
        <v-card-text>
          <v-text-field v-model="inputValue" label="请输入标题"></v-text-field>
        </v-card-text>
        <v-card-actions>
          <v-btn text @click="closeModal">关闭模态框</v-btn>
          <v-btn color="primary" @click="submitForm">提交</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-container>
</template>

<style>
.container {
  position: relative;
}

.centered-row {
  align-items: center;
}

.centered-col {
  display: flex;
  justify-content: center;
  margin-top: 100px;
}

.divider {
  border: none;
  border-top: 1px solid #ccc;
  margin-top: 10px;
}
</style>

<script>
import axios from "axios";
export default {
  data: () => ({
    snackbar: false,
    text: ``,
    color: "success",
    text_ico: "mdi-check-circle",
    desserts: [],
    modalOpen: false, // 控制模态框的显示与隐藏
    inputValue: "", // 表单输入框的值
    searchKeyword: "",
    selectAll: false, // 控制全选复选框的状态
    selectedItems: [], // 已选中的表格行数据
  }),
  methods: {
    openModal() {
      this.modalOpen = true; // 打开模态框
    },
    closeModal() {
      this.modalOpen = false; // 关闭模态框
    },
    alertmsg(text, ico, color) {
      if (ico === undefined) {
        ico = "mdi-check-circle";
      }
      if (color === undefined) {
        color = "success";
      }
      this.color = color;
      this.text = text;
      this.text_ico = ico;
      this.snackbar = true;
    },
    submitForm() {
      // 在这里可以处理表单提交逻辑
      axios
        .post("/api/spider/add", { name: this.inputValue }) // 发送GET请求到后端API
        .then((response) => {
          this.getProject();
          console.log(response.data);
          this.alertmsg(response.data.msg);
        })
        .catch((error) => {
          // 处理请求错误
          this.alertmsg("请求失败", "mdi-cancel", "error");
          console.error(error);
        });
      this.closeModal(); // 提交后关闭模态框
    },
    filterEntries() {
      // 当搜索框输入内容时触发过滤操作
      // 这里只是修改了搜索关键字，computed 属性会自动触发重新计算 filteredDesserts
    },
    toggleAllSelection() {
      // 全选复选框状态改变时触发
      if (this.selectAll) {
        this.selectedItems = [...this.filteredDesserts];
      } else {
        this.selectedItems = [];
      }
    },
    isSelected(item) {
      // 检查一个项目是否被选中
      return this.selectedItems.includes(item);
    },
    deleteSelectedItems() {
      // 删除选中项按钮点击事件处理
      this.desserts = this.desserts.filter(
        (item) => !this.selectedItems.includes(item)
      );
      axios
        .post("/api/project/del", { data: this.selectedItems }) // 发送GET请求到后端API
        .then((response) => {
          this.getProject();
          console.log(response.data);
          this.alertmsg(response.data.msg);
          this.getProject();
        })
        .catch((error) => {
          // 处理请求错误
          this.alertmsg("请求失败", "mdi-cancel", "error");
          console.error(error);
        });
      this.selectedItems = []; // 清空已选中的项
    },
    getProject() {
      axios
        .get("/api/spider/project") // 发送GET请求到后端API
        .then((response) => {
          console.log(response);
          this.desserts = response.data.data;
        })
        .catch((error) => {
          // 处理请求错误
          this.alertmsg("获取项目列表失败", "mdi-cancel", "error");
          console.error(error);
        });
    },
    navigateToItem(name) {
      // 调用编程式导航方法，根据 item.name 进行导航
      this.$router.push({ name: "spidertest", params: { itemName: name } });
    },
  },
  computed: {
    filteredDesserts() {
      // 根据搜索关键字过滤表格数据
      return this.desserts.filter((item) => {
        return item.name
          .toLowerCase()
          .includes(this.searchKeyword.toLowerCase());
      });
    },
  },
  created() {
    this.getProject();
  },
};
</script>
